//
//  NetworkTools.m
//  测试-04-封装AFN框架
//  Created by male on 15/10/15.
//  Copyright © 2015年 itheima. All rights reserved.
//

#import "NetworkTools.h"
#import "UserAccountViewModel.h"

/// 网络工具协议
@protocol NetworkToolsProxy <NSObject>

/// 网络请求方法
///
/// @param method     HTTP 请求方法
/// @param URLString  URLString
/// @param parameters 参数字典
/// @param success    成功回调
/// @param failure    失败回调
///
/// @return NSURLSessionDataTask
@optional
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure;
@end

/// 遵守网络协议 - 为了能够欺骗 Xcode 给一个智能提示，以及编译通过！
@interface NetworkTools() <NetworkToolsProxy>


@end

@implementation NetworkTools

// MARK: - 微博数据方法
-(void)loadStatusfinished:(finishedBlock)finished{
    
    NSString * urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSString * token = [UserAccountViewModel shareUserAccount].accessToken;
    
    NSDictionary * params = @{@"access_token":token};
    [self request:GET URLString:urlString parameters:params finished:finished];

}
// MARK: 用户相关方法
/**
 * 加载用户信息
 *
 * @param uid          uid
 * @param accessToken accessToken
 * @param finished     完成回调
 */
-(void)loadUserInfoUid:(NSString *)uid accessToken:(NSString*)accessToken finished:(finishedBlock)finished{
    
    NSString * urlString = @"https://api.weibo.com/2/users/show.json";
    
    NSDictionary * params = @{@"uid":uid,@"access_token":accessToken};

    [self request:GET URLString:urlString parameters:params finished:finished];
}
// MARK: - OAuth相关方法
NSString * appKey = @"1898065063";
NSString * redirectUrl = @"http://www.baidu.com";
NSString * appSecret = @"a7b750184049fa1ff1e2d08badf0f201";
//获取授权码 url
-(NSURL *)url{
    
    NSString * urlStr = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",appKey,redirectUrl];
    NSURL * url = [NSURL URLWithString:urlStr];
    return  url;
}
// 加载 token
-(void)loadAccessToken:(NSString *)code finished:(finishedBlock)finished{
    
    NSString * urlString = @"https://api.weibo.com/oauth2/access_token";
    NSDictionary * parms = @{@"client_id":appKey,
        @"client_secret":appSecret,
        @"grant_type":@"authorization_code",
        @"code":code,
        @"redirect_uri":redirectUrl};
    NSLog(@"%@",parms);
    [self request:POST URLString:urlString parameters:parms finished:finished];
}
+ (instancetype)sharedTools {
    static NetworkTools *tools;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 注意：末尾需要包含 '/'
        //NSURL *baseURL = [NSURL URLWithString:@"http://httpbin.org/"];
        
        tools = [[self alloc] initWithBaseURL:nil];
        
        // 设置反序列化格式
        tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    });
    
    return tools;
}

- (void)request:(HMRequestMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(finishedBlock)finished {
    
    NSString *methodName = (method == GET) ? @"GET" : @"POST";

    // dataTaskWithHTTPMethod本类没有实现方法，但是父类实现了
    // 在调用方法的时候，如果本类没有提供，直接调用父类的方法，AFN 内部已经实现！
    [[self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        
        finished(responseObject, nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
        finished(nil, error);
    }] resume];
    
}

@end
